<template>
  <a-modal :title="type === 0 ? '新增消息' : '编辑消息'" :width="500" :visible="visible" :body-style="{ paddingBottom: '80px' }" @close="onClose">
    <a-form :model="form" :rules="rules" layout="vertical" ref="formRef">
      <a-form-item label="标题：" name="title">
        <a-input v-model:value="form.title" placeholder="请输入消息标题" autocomplete="off" @change="changeForm" />
      </a-form-item>

      <a-form-item label="消息内容：" name="content">
        <a-textarea v-model:value="form.content" placeholder="请输入消息内容" :rows="5" @change="changeForm" />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-row type="flex" justify="end">
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="plusAdmin">{{ type === 0 ? '添加' : '修改' }}</a-button>
      </a-row>
    </template>
  </a-modal>
</template>

<script lang="ts">
import { ValidateErrorEntity } from 'ant-design-vue/es/form/interface'
import { defineComponent, onUpdated, reactive, ref, Ref, toRaw, watch } from 'vue'
import { post, get, put } from '../../../utils/request/request'
import { message } from 'ant-design-vue'

interface FormState {
  title: string
  content: string
}
const formRef = ref()
const form = reactive({
  title: '',
  content: ''
})

// drawer
const useDrawerEffect = () => {
  const visible = ref<boolean>(false)
  const showDrawer = () => {
    visible.value = true
  }
  const onClose = () => {
    form.title = ''
    form.content = ''
    visible.value = false
  }
  return { visible, showDrawer, onClose }
}

//表格操作
const useFormEffect = (visible: Ref<boolean>, context: any, id: number) => {
  const isChange = ref<boolean>(false)
  const rules = {
    title: [{ required: true, message: '请输入消息标题', trigger: 'blur' }],
    content: [{ required: true, message: '请输入消息内容', trigger: 'blur' }]
  }
  const { postData, putData } = useHttpEffect(visible, context)
  const plusAdmin = () => {
    console.log(id)
    formRef.value
      .validate()
      .then(() => {
        if (id) {
          if (isChange.value) {
            console.log(1)
            putData(id)
          } else {
            console.log(2)
            formRef.value.resetFields()
            visible.value = false
          }
        } else {
          console.log(3)
          postData()
        }
        formRef.value.resetFields()
      })
      .catch((error: ValidateErrorEntity<FormState>) => {
        console.log(error)
      })
  }
  const changeForm = () => {
    isChange.value = true
  }
  return { isChange, changeForm, rules, plusAdmin }
}

// 网络请求
const useHttpEffect = (visible: Ref<boolean>, context: any) => {
  const token: string = localStorage.getItem('token') as string

  const postData = async () => {
    const res: any = await post('/admin/api/v1/message', toRaw(form), token)
    console.log(res)
    if (res?.status_code === 0) {
      message.success('添加成功', 3)
      context.emit('getData')
      visible.value = false
    } else {
      message.error(res.status_msg, 3)
    }
  }

  // 获取标题内容
  const getData = async (id: number) => {
    const res: any = await get(`/admin/api/v1/message/${id}`, token)
    console.log(res)
    form.title = res?.data?.title
    form.content = res?.data?.content
  }

  const putData = async (id: number) => {
    console.log('修改')
    const res: any = await put(`/admin/api/v1/message/${id}`, toRaw(form), token)
    if (res?.status_code === 0) {
      console.log('修改成功')
      message.success('修改成功', 3)
      context.emit('getData')
      visible.value = false
    } else {
      console.log('修改失败')
      message.error(res.status_msg, 3)
    }
  }
  return { postData, getData, putData }
}

export default defineComponent({
  props: ['type', 'id'], //type: 0新增 1编辑
  setup(props, context) {
    const id = props.id
    const token: string = localStorage.getItem('token') as string
    const { visible, showDrawer, onClose } = useDrawerEffect()
    const { isChange, changeForm, rules, plusAdmin } = useFormEffect(visible, context, id)
    const { getData } = useHttpEffect(visible, context)

    const newId = ref<number>(0)

    watch(
      () => props.id,
      (propsId) => {
        newId.value = propsId
      }
    )

    onUpdated(() => {
      if (visible.value && props.type == 1) {
        getData(newId.value)
      }
    })

    return {
      formRef,
      form,
      isChange,
      changeForm,
      rules,
      visible,
      showDrawer,
      plusAdmin,
      onClose,
      token
    }
  }
})
</script>
